package service

import (
	"frame/internal/app/user/domain"
	"frame/internal/app/user/repository/mysql"
)

type UserService struct {
	userRepo mysql.UserRepository
}

// NewUserService 创建一个新的用户服务
func NewUserService(userRepo mysql.UserRepository) *UserService {
	return &UserService{userRepo: userRepo}
}

// CreateUser 创建新用户
func (s *UserService) CreateUser(id, name, email, street, city, state, country string) (*domain.User, error) {
	user, err := domain.NewUser(id, name, email, street, city, state, country)
	if err != nil {
		return nil, err
	}

	if err := s.userRepo.Save(user); err != nil {
		return nil, err
	}

	return user, nil
}

// UpdateUserEmail 更新用户邮箱
func (s *UserService) UpdateUserEmail(id, newEmail string) (*domain.User, error) {
	user, err := s.userRepo.FindByID(id)
	if err != nil {
		return nil, err
	}

	if err := user.ChangeEmail(newEmail); err != nil {
		return nil, err
	}

	if err := s.userRepo.Save(user); err != nil {
		return nil, err
	}

	return user, nil
}

// UpdateUserAddress 更新用户地址
func (s *UserService) UpdateUserAddress(id, street, city, state, country string) (*domain.User, error) {
	user, err := s.userRepo.FindByID(id)
	if err != nil {
		return nil, err
	}

	if err := user.ChangeAddress(street, city, state, country); err != nil {
		return nil, err
	}

	if err := s.userRepo.Save(user); err != nil {
		return nil, err
	}

	return user, nil
}
